import sys
import os
import time
import subprocess
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QSplitter, QTreeView, QTabWidget, QStatusBar, 
    QVBoxLayout, QWidget, QTextEdit, QGraphicsView, QGraphicsScene, QGraphicsRectItem,
    QToolBar, QMessageBox, QPushButton, QLabel, QMenu, 
    QInputDialog, QFileDialog, QDialog, QDialogButtonBox, QSizePolicy
)
from PyQt6.QtGui import (
    QIcon, QTextCharFormat, QColor, QFont, QPen, QBrush, QPainterPath, QFileSystemModel,
    QTextCursor, QPalette, QStandardItemModel, QStandardItem, QSyntaxHighlighter, 
    QRegularExpressionValidator, QAction, QPainter
)
from PyQt6.QtCore import (
    Qt, QRectF, QPointF, QModelIndex, QFileInfo, QSortFilterProxyModel,
    QRegularExpression, QTimer, QSize
)
import git
from git import Repo, GitCommandError, InvalidGitRepositoryError






# ===================== 仓库文件浏览器 =====================
class RepoExplorer(QTreeView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setHeaderHidden(True)
        self.setEditTriggers(QTreeView.EditTrigger.NoEditTriggers)
        
        # 设置深色主题
        palette = self.palette()
        palette.setColor(QPalette.ColorRole.Base, QColor("#1e1e1e"))
        palette.setColor(QPalette.ColorRole.Text, QColor("#d4d4d4"))
        self.setPalette(palette)
        
        self.doubleClicked.connect(self.handle_double_click)
    
    def load_repo(self, repo_path):
        # 创建文件系统模型
        model = QFileSystemModel()
        model.setRootPath(repo_path)
        
        # 设置过滤器和列
        proxy_model = QSortFilterProxyModel()
        proxy_model.setSourceModel(model)
        proxy_model.setFilterRegularExpression(r"^[^\.].*")  # 过滤掉隐藏文件
        
        self.setModel(proxy_model)
        self.setRootIndex(proxy_model.mapFromSource(model.index(repo_path)))
        
        # 隐藏不必要的信息列
        for i in range(1, 3):
            self.header().hideSection(i)
    
    def handle_double_click(self, index):
        proxy_model = self.model()
        model = proxy_model.sourceModel()
        source_index = proxy_model.mapToSource(index)
        path = model.filePath(source_index)


        if os.path.isfile(path):
            # 获取主窗口实例
            main_window = self.window()
            if hasattr(main_window, 'open_file_in_editor'):
                main_window.open_file_in_editor(path)
        